//
//  SSDKPluginQrCodeUtil.m
//  SuperSDKPluginTools
//
//  Created by 涂俊 on 2018/1/3.
//  Copyright © 2018年 WYHT. All rights reserved.
//

#import "SSDKPluginQrCodeUtil.h"

@implementation SSDKPluginQrCodeUtil

+ (UIImage *)qrImageForString:(NSString *)string
                    imageSize:(CGFloat)imageSize
                       margin:(CGFloat) margin
                          tip:(NSString *)tip {
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKey:@"inputMessage"];//通过kvo方式给一个字符串，生成二维码
    [filter setValue:@"H" forKey:@"inputCorrectionLevel"];//设置二维码的纠错水平，越高纠错水平越高，可以污损的范围越大
    CIImage *outPutImage = [filter outputImage];//拿到二维码图片
    return [[self class] createNonInterpolatedUIImageFormCIImage:outPutImage
                                                      withSize:imageSize
                                                        margin:margin
                                                           tip:tip];
}

+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image
                                            withSize:(CGFloat) size
                                              margin:(CGFloat) margin
                                                 tip:(NSString *)tip {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN((size - 2*margin)/CGRectGetWidth(extent), (size - 2*margin)/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    //创建一个DeviceGray颜色空间
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    //CGBitmapContextCreate(void * _Nullable data, size_t width, size_t height, size_t bitsPerComponent, size_t bytesPerRow, CGColorSpaceRef  _Nullable space, uint32_t bitmapInfo)
    //width：图片宽度像素
    //height：图片高度像素
    //bitsPerComponent：每个颜色的比特值，例如在rgba-32模式下为8
    //bitmapInfo：指定的位图应该包含一个alpha通道。
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    //创建CoreGraphics image
    CGImageRef bitmapImage = [[CIContext contextWithOptions:nil] createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    // 返回二维码原图
    UIImage *outputImage = [UIImage imageWithCGImage:scaledImage];
    
    // 如果需要边缘留白边
    if (margin > 0) {
        UIGraphicsBeginImageContext(CGSizeMake(size, size));
        CGContextRef context = UIGraphicsGetCurrentContext();
        // 白底
        CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
        CGContextFillRect(context , CGRectMake(0, 0, size, size));
        // 二维码居中
        [outputImage drawInRect:CGRectMake(margin, margin, outputImage.size.width, outputImage.size.height)];
        outputImage= UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    // 如果需要在底部添加文字
    if (tip != nil && tip.length != 0) {
        //字体大小是图片的1/8，或者是能容纳下所有文字的最大字体
        CGFloat textSize = MIN(size * 0.8 / tip.length, size * 0.8 / 8);
        //文字是另外加的一行。如果二维码有margin，则额外的行高需要减去margin
        CGFloat textHeight = MAX(textSize * 1.2 - margin, 0);
        CGSize newSize = CGSizeMake(outputImage.size.width, outputImage.size.height + textHeight);
        UIGraphicsBeginImageContext(newSize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        //绘制底部白边
        CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
        CGContextFillRect(context , CGRectMake(0, outputImage.size.height, outputImage.size.width, textHeight));
        //绘制二维码图片
        [outputImage drawInRect:CGRectMake(0, 0, outputImage.size.width, outputImage.size.height)];
        //绘制文字
        CGContextDrawPath(bitmapRef, kCGPathStroke);
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:textSize]};
        CGRect sizeToFit = [tip boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, textSize) options:NSStringDrawingUsesDeviceMetrics attributes:attributes context:nil];
        CGContextSetFillColorWithColor(bitmapRef, [UIColor blueColor].CGColor);
        [tip drawAtPoint:CGPointMake((newSize.width - sizeToFit.size.width)/2, outputImage.size.height - margin) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:textSize]}];
        outputImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return outputImage;
}

@end
